package memcached

import (
	"github.com/bradfitz/gomemcache/memcache"
	"time"
)

type WrapperMemcached struct {
	Name  string
	cache *memcache.Client
}

type Setting struct {
	Name string `mapstructure:"name"`
	// 超时时间，连接超时时间和socket超时时间
	Timeout time.Duration `mapstructure:"do_with_timeout"`
	// 每个地址的最大连接数量
	MaxIdleConn int      `mapstructure:"max_pool_size"`
	Addr        []string `mapstructure:"addr"`
}

// InitMemcached 获取memcached实例
// 用法：WrapperMemcached.Cache.Get()
func InitMemcached(setting Setting) *WrapperMemcached {
	if len(setting.Addr) == 0 || setting.Name == "" {
		panic("name or addr cannot be null")
	}
	cache := memcache.New(setting.Addr...)
	if setting.Timeout != 0 || setting.Timeout.Nanoseconds() != 0 {
		cache.Timeout = setting.Timeout * time.Second
	}
	if setting.MaxIdleConn != 0 {
		cache.MaxIdleConns = setting.MaxIdleConn
	}

	return &WrapperMemcached{Name: setting.Name, cache: cache}
}
